import './TagList.scss';
import { watch, computed, defineComponent, onMounted, ref, nextTick, VNodeRef } from 'vue';
import type { PropType } from 'vue';
import { ElTag, ElImage, ElTooltip } from 'element-plus';

export default defineComponent({
    name: 'TagList',
    props: {
        disabled: {
            type: Boolean,
            default: false
        },
        theme: {
            type: String,
            default: 'default'
        },
        type: {
            type: Number,
            default: 0
        },
        dataList: {
            type: Array as PropType<any>,
            default: () => []
        }
    },
    emit: ['del', 'clickMore'],
    setup(props, { emit }) {
        const tagBoxIdName = ref<string>(`select_items_tag_box_${Math.random().toString(36).substring(2)}`);
        const selectItemsTagBoxRef = ref<HTMLDivElement | VNodeRef | null>(null);
        const restTags = ref<any[]>([]);
        const default_images = ref({
            default_user_avatar: 'https://img.static-keyid.cn/toolspace/scrm/2023/08/169348396644985g3f4wnjb7jzqvx.png',
            default_group_logo: 'https://img.static-keyid.cn/toolspace/scrm/2023/08/1693483961522k4qsjw4hwuno1h1r.png'
        });
        const showList = ref<any[]>([]);
        watch(
            () => props.dataList,
            () => {
                if (props.dataList.length) {
                    nextTick(() => updateLayout());
                } else {
                    showList.value = [];
                }
            },
            { immediate: true, deep: true }
        );
        const clickTag = (isMore = false) => {
            isMore && !props.disabled && emit('clickMore');
        };
        const delItem = (index: number) => {
            !props.disabled && emit('del', index);
        };
        const initWidth = () => {
            const list = [...props.dataList];
            if (list.length) {
                const cont: any = document.querySelector(`#${tagBoxIdName.value}`);
                const tagDomList = Array.from(cont.getElementsByClassName('tag-item'));
                const res: any = tagDomList.reduce(
                    (pre: any, element: any, index: number) => {
                        if (!pre.flag) {
                            const offsetLeft = element.offsetLeft;
                            const offsetWidth = element.offsetWidth;
                            if (offsetLeft < pre.offsetLeft) {
                                if (pre.offsetLeft + pre.offsetWidth + 46 > cont.offsetWidth + cont.offsetLeft) {
                                    pre.index--;
                                }
                                pre.flag = true;
                            } else {
                                pre.offsetLeft = offsetLeft;
                                pre.offsetWidth = offsetWidth;
                                pre.index = index + 1;
                                pre.flag = false;
                            }
                        }
                        return pre;
                    },
                    { flag: false, offsetLeft: 0, offsetWidth: 0, index: 0 }
                );
                const { flag, index } = res;
                if (flag) {
                    restTags.value.splice(0);
                    restTags.value = list.splice(index - 1);
                    list.push({ isMore: true });
                }
            }
            showList.value = [...list];
        };
        const updateLayout = () => {
            showList.value = [...props.dataList];
            setTimeout(() => initWidth(), 0);
        };
        onMounted(() => {
            window.onresize = () => updateLayout();
        });
        return {
            selectItemsTagBoxRef,
            tagBoxIdName,
            default_images,
            showList,
            restTags,
            clickTag,
            delItem
        };
    },
    render() {
        const {
            selectItemsTagBoxRef,
            tagBoxIdName,
            disabled,
            type,
            theme,
            dataList,
            default_images,
            restTags,
            showList,
            clickTag,
            delItem
        } = this;
        const showTags = (tag: any, index: number) => {
            return (
                <ElTag
                    class={'tag-item'}
                    plain
                    type={theme}
                    closable={!disabled}
                    size={type === 0 ? '' : 'large'}
                    onClick={() => clickTag()}
                    onClose={() => delItem(index)}>
                    {type === 0 ? (
                        tag.name
                    ) : (
                        <div class={'tag-staff'}>
                            <ElImage
                                class={'tag-avatar'}
                                src={tag.avatar}
                                vSlots={{
                                    error: () => {
                                        return (
                                            <ElImage class={'tag-avatar'} src={default_images.default_user_avatar} />
                                        );
                                    }
                                }}
                            />
                            <span class={'tag-name'}>{tag.name}</span>
                        </div>
                    )}
                </ElTag>
            );
        };
        const moreTags = (tag: any, index: number) => {
            const content = (
                <div class={'rest-tags'}>
                    {restTags.map((tag: any, index: number) => {
                        return showTags(tag, index);
                    })}
                </div>
            );
            return (
                <ElTooltip
                    effect="light"
                    placement="top-start"
                    popper-class={'select-items-tag-tooltip'}
                    disabled={!disabled}
                    vSlots={{ content }}>
                    <ElTag
                        class={'tag-item tag-more'}
                        plain
                        type={theme}
                        size={type === 0 ? '' : 'large'}
                        onClick={() => clickTag(tag.isMore)}>
                        ...
                    </ElTag>
                </ElTooltip>
            );
        };

        return (
            <>
                <div ref={selectItemsTagBoxRef} class={'select-items-tag-box'} id={tagBoxIdName}>
                    {showList.map((tag: any, index: number) => {
                        if (tag.isMore) {
                            return moreTags(tag, index);
                        } else {
                            return showTags(tag, index);
                        }
                    })}
                </div>
            </>
        );
    }
});
